package com.mdxl.service;

import com.mdxl.Entity.City;
import com.mdxl.dao.note.CityDao;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;


import java.util.concurrent.TimeUnit;


@Service
public class RedisService {
    @Autowired
    private CityDao cityDao;
    @Autowired
    private RedisTemplate redisTemplate;
    //add
    public void add(String id,String name){
        ValueOperations<String,String> valueOperations =redisTemplate.opsForValue();
        valueOperations.set(id, name);
    }
    //delete
    public void delete(String id){
        ValueOperations<String,String> valueOperations=redisTemplate.opsForValue();
        valueOperations.getOperations().delete(id);
    }
    //update
    public void update(String id,String name){
        ValueOperations<String,String> valueOperations =redisTemplate.opsForValue();
        valueOperations.set(id, name);
    }
    //search
    public String get(String id){
        ValueOperations<String,String> valueOperations =redisTemplate.opsForValue();
        return valueOperations.get(id);
    }
    //先从Redis中获取
    public City getCity(int id){
        //从缓存中获取city信息
        String key ="city_" + id;
        ValueOperations<String,City> valueOperations =redisTemplate.opsForValue();
        boolean hashKey =redisTemplate.hasKey(key);
        if (hashKey){
            City city =valueOperations.get(key);
            return city;
        }
        City city =cityDao.gainCity(id);
        valueOperations.set(key,city,1, TimeUnit.SECONDS);
        return city;
    }
    public void addCity(City city){
        cityDao.addCity(city);
    }
    public int updateCity(City city){
        int set = cityDao.updateCity(city);
        //缓存存在，删除缓存
        String key ="city_" + city.getId();
        boolean hashKey = redisTemplate.hasKey(key);
        if (hashKey){
            redisTemplate.delete(key);
        }
        return set;
    }
    public int deleteCity(int id){
        int set = cityDao.deleteCity(id);
        //缓存存在，删除缓存
        String key ="city_" + id;
        boolean hashKey = redisTemplate.hasKey(key);
        if (hashKey){
            redisTemplate.delete(key);
        }
        return set;
    }

}
